package com.sec.etech.chain.customer.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.chain.customer.dao.CusCustomerDao;
import com.sec.etech.chain.customer.entity.MergeLog;
import com.sec.etech.chain.customer.entity.ProjCustomer;
import com.sec.etech.chain.customer.mapper.MergeLogMapper;
import com.sec.etech.chain.customer.mapper.ProjCustomerMapper;
import com.sec.etech.chain.customergroup.entity.CustomerGroup;
import com.sec.etech.chain.customergroup.mapper.CustomerGroupMapper;
import com.sec.etech.chain.customergroup.service.CustomerGroupService;
import com.sec.etech.common.fanutil.FanUtil;
import com.sec.etech.org.service.EtechUserUtil;
import com.sec.etech.presale.mapper.PreProjectBasicinfoMapper;
import com.sec.etech.presale.model.PreProjectBasicinfo;
import com.sec.etech.project.mapper.ProjectMapper;
import com.sec.etech.project.model.Project;
import com.sec.etech.sys.msg.EtechMailService;
import com.sec.etech.sys.msg.model.EtechEmailMessage;
import com.sec.etech.sys.service.EtechDictServiceImpl;
import com.sec.etech.sys.util.ContextUtil;
import com.sec.etech.sys.util.RequestHolder;
import org.openbpm.base.core.id.IdUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @version : 1.0
 * @auther : 老邓
 * @date : 2020/12/17 10:40
 * @description:
 */
@Service
public class CusCustomerService {

    @Resource
    ProjCustomerMapper customerMapper;
    @Resource
    EtechMailService etechMailService;
    @Resource
    CustomerGroupService customerGroupService;
    @Resource
    EtechDictServiceImpl dictService;
    @Resource
    PreProjectBasicinfoMapper preProjectMapper;
    @Resource
    ProjectMapper projectMapper;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    MergeLogMapper mergeLogMapper;
    @Resource
    CustomerGroupMapper customerGroupMapper;
    @Resource
    CusCustomerDao cusCustomerDao;

    //数据重复性检查
    public Boolean checkData(String customerid, String customername, String scope) {
        List<String> customerids = cusCustomerDao.getCustomeridByName(customername);
        if (customerids.isEmpty()) return true;
        else if (scope.equals("edt") && customerids.get(0).equals(customerid)) return true;
        return false;
    }

    public Boolean checkData(String customername, String scope) {
        return checkData("0", customername, scope);
    }

    //获取最新的客户代号
    public String getNewCustomercode() {
        return cusCustomerDao.getNewCustomercode();
    }

    //删除客户
    public Boolean del(String customerid) {
        cusCustomerDao.del(customerid);
        return true;
    }

    //获取关联项目
    public List<Long> getProjects(String customerid) {
        return cusCustomerDao.getProjects(customerid);
    }

    //编辑关联项目,返回最新的客户机组数量
    public String addProjects(String customerid, String projectids) {
        cusCustomerDao.addProjects(customerid, projectids);
        return cusCustomerDao.getOrdersCount(customerid);
    }

    //更新所有客户机组数量
    public Boolean resetOrdersCount() {
        cusCustomerDao.resetOrdersCount();
        return true;
    }

    public void add(Long id, String name, String source, String groupIdJson, String npdfs1id) {
        String customercode = this.getNewCustomercode();
        CustomerGroup customerGroup = customerGroupService.generateOne("", name, groupIdJson);

        ProjCustomer customer = new ProjCustomer();
        customer.setCustomerid(id);
        customer.setCustomercode(customercode);
        customer.setCustomername(name);
        customer.setCustomergroupid(Long.parseLong(customerGroup.getCustomergroupid()));
        customer.setGroupIdJson(groupIdJson);
        customer.setStatusId(429502380176310273L); //正常
        FanUtil.setBaseData(customer);
        customerMapper.insert(customer);

        customerGroupService.add(customerGroup, customer.getCustomercode());

        dictService.deleteDictCache("cusCustomer");


        String sql = "SELECT \n" +
                "a.*,\n" +
                "IFNULL(b.reformname,'') AS reformname,\n" +
                "IFNULL(c.schemename,'') AS schemename,\n" +
                "IFNULL(d.originname,'') AS originname,\n" +
                "IFNULL(e.orderdprtname,'') AS orderdprtname,\n" +
                "IFNULL(f.dutyname,'') AS dutyname,\n" +
                "IFNULL(g.customergroupfullname,'') AS customergroupfullname,\n" +
                "IFNULL(h.institutename,'') AS institutename,\n" +
                "IFNULL(i.thermalperformname,'') AS thermalperformname,\n" +
                "IFNULL(j.platename,'') AS platename,\n" +
                "IFNULL(j.fieldname,'') AS fieldname,\n" +
                "IFNULL(k.driveobjectname,'') AS driveobjectname,\n" +
                "IFNULL(l.supplyscopename,'') AS supplyscopename,\n" +
                "IFNULL(m.provincename,'') AS provincename,\n" +
                "IFNULL(n.marketname,'') AS marketname,\n" +
                "concat(IFNULL(o.cycletypecode,''),' ',IFNULL(o.cycletypename,'')) AS cycletypename,\n" +
                "CONCAT(IFNULL(p.model,''),' ',IFNULL(p.types,'')) AS modelname,\n" +
                "IFNULL(q.customername,'') AS customername\n" +
                "\n" +
                "FROM `pre_project_basicinfo` AS a\n" +
                "LEFT JOIN proj_project_z_reform AS b ON a.reformid = b.reformid\n" +
                "LEFT JOIN proj_project_z_scheme AS c ON a.schemeid = c.schemeid\n" +
                "LEFT JOIN proj_project_z_origin AS d ON a.originid = d.originid\n" +
                "LEFT JOIN proj_project_z_orderdprt AS e ON a.orderdprtid = e.orderdprtid\n" +
                "LEFT JOIN proj_project_z_duty AS f ON a.dutyid = f.dutyid\n" +
                "LEFT JOIN proj_project_z_customergroup AS g ON a.customergroupid = g.customergroupid\n" +
                "LEFT JOIN proj_project_z_institute AS h ON a.instituteid = h.instituteid\n" +
                "LEFT JOIN prod_model_z_thermalperform AS i ON a.thermalperformid = i.thermalperformid\n" +
                "LEFT JOIN proj_project_z_plate AS j ON a.plateid = j.plateid\n" +
                "LEFT JOIN proj_project_z_driveobject AS k ON a.driveobjectid = k.driveobjectid\n" +
                "LEFT JOIN proj_project_z_supplyscope AS l ON a.supplyscopeid = l.supplyscopeid\n" +
                "LEFT JOIN proj_project_z_province AS m ON a.provinceid = m.provinceid\n" +
                "LEFT JOIN proj_project_z_market AS n ON a.marketid = n.marketid\n" +
                "LEFT JOIN prod_model_z_cycle_type AS o ON a.cycletypeid = o.cycletypeid\n" +
                "LEFT JOIN prod_model AS p ON a.modelid = p.modelid\n" +
                "LEFT JOIN proj_customer AS q ON a.customerid = q.customerid" +
                " WHERE a.npdfs1id = {}";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(StrUtil.format(sql, npdfs1id));
        Map<String, Object> dataMap = mapList.get(0);
        String s1Num = dataMap.get("num").toString();

        String sql2 = "SELECT\n" +
                "\t* \n" +
                "FROM\n" +
                "\t`pre_project_customergroups` AS t0\n" +
                "\tLEFT JOIN proj_project_z_customergroup AS t1 ON t0.customergroupid = t1.customergroupid \n" +
                "WHERE\n" +
                "\tnpdfs1id = {}";
        List<Map<String, Object>> mapList2 = jdbcTemplate.queryForList(StrUtil.format(sql2, npdfs1id));
        List<String> list = FanUtil.mapListToList(mapList2, "customergroupfullname");

        EtechEmailMessage emailMessage = new EtechEmailMessage();
        String subject = "【客户管理】售前项目 " + s1Num + " 新增客户";
        List<String> toList = EtechUserUtil.getUserIdsByRoleCode("R_proj_customer_admin");
        String content = "<div style=\"font-size:16px; font-family: 等线\">\n" +
                "    <div style=\"font-family: 等线\">您好，售前项目 " + s1Num + " 新增客户：</div>\n" +
                "    <br/>\n" +
                "    <div style=\"margin-left:30px;\">\n" +
                "    <table style=\"font-size:16px;\">\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">客户编号：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + customercode + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">客户名称：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + name + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">添加来源：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + source + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">添加人员：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + ContextUtil.getCurrentUserName() + "</td>\n" +
                "        </tr>\n" +
                "    </table>\n" +
                "    </div>\n" +
                "    <br/>\n" +
                "    <a href=\"" + RequestHolder.getUrl() + "/index.html?link=/form/formCustSql/view/formCustSqlView.html?code=projCustomer|客户管理列表\" style=\"text-decoration: none; color:#0070c0; font-weight:bold\">点击进入客户管理列表（请使用谷歌浏览器查看）</a>\n" +
                "    <br/>\n" +
                "    <br/>\n" +
                "    <br/>\n" +


                "    <div style=\"font-family: 等线\">售前项目相关信息如下 ：</div>\n" +
                "    <br/>\n" +
                "    <div style=\"margin-left:30px;\">\n" +
                "    <table style=\"font-size:16px;\">\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目编号：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + s1Num + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目名称：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("projectname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目属性：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("reformname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">产品规划：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("schemename")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">销售部门：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("originname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">售前技术归口：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("orderdprtname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">售前技术责任：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("dutyname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">投资方：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(String.join("、", list)) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">所属集团：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("customergroupfullname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">设计院：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("institutename")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">业主(电厂)名称：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("customername")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">机组形式：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("thermalperformname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">销售经理：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("salesmanageruname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">机组台数(台)：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("quantity")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">产品板块：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("platename")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">产品领域：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("fieldname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">驱动对象：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("driveobjectname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">供货范围：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("supplyscopename")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目国家：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("country")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目省份：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("provincename")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目市场：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("marketname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">产品编号：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("modelname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">联合循环布置方式：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("cycletypename")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">改造标的：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("reformordersname")) + "</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\" font-family: 等线; color:#7f7f7f; font-weight:bold; text-align:right\">项目备注：</td>\n" +
                "            <td style=\" font-family: 等线;\">" + FanUtil.toStringIfNullToEmpty(dataMap.get("projectremark")) + "</td>\n" +
                "        </tr>\n" +

                "    </table>\n" +
                "    </div>\n" +
                "    <br/>\n" +
                "    <a href=\"" + RequestHolder.getUrl() + "/index.html#?link=/form/formCustSql/view/formCustSqlView.html?code=preProjectList|售前项目列表\" style=\"text-decoration: none; color:#0070c0; font-weight:bold\">点击进入售前项目列表（请使用谷歌浏览器查看）</a>\n" +
                "    <br/>\n" +


                "    <br/>\n" +
                "    <div style=\"margin-top: 10px; color: red; font-size: 14px\">此邮件为平台自动发送，请勿回复！</div>\n" +
                "</div>\n";


        emailMessage.setSubject(subject);
        emailMessage.setTo(String.join(",", toList));
        emailMessage.setBcc("39300101");
        emailMessage.setHtmlContent(content);
        etechMailService.sendMail(emailMessage);


    }


    /**
     * 根据项目 id 查询该项目的客户
     *
     * @param type      s 代表售前项目 p 代表执行项目
     * @param projectId 可能是 pre_project_basicinfo.npdfs1id  或 proj_project.projectid 两者值一样
     * @return
     */
    public String getCustomerId(String type, String projectId) {
        if ("s".equals(type)) {
            PreProjectBasicinfo preProject = preProjectMapper.selectById(projectId);
            return FanUtil.toStringIfNullToEmpty(preProject.getCustomerid());

        } else if ("p".equals(type)) {
            Project project = projectMapper.selectById(projectId);
            return FanUtil.toStringIfNullToEmpty(project.getCustomerid());

        } else {
            throw new RuntimeException("未知的 type=[" + type + "] 请先选择售前项目或者工程项目！");
        }


    }


    @Transactional
    public void merge(JSONObject req) {
        if (req == null) {
            throw new RuntimeException("请求参数为空！");
        }


        List<Long> leftIdArr = JSONObject.parseArray(req.getString("leftIdArr"), Long.class);
        Long rightId = req.getLong("rightId");

        if (leftIdArr == null || leftIdArr.size() == 0) {
            throw new RuntimeException("左侧要合并的数据为空！");
        }
        if (rightId == null) {
            throw new RuntimeException("右侧合并到的数据为空！");
        }

        // String leftIdSequence = String.join(",", leftIdArr);
        Long rightCustomerGroupId = customerMapper.getCustomerGroupId(rightId);
        if (StrUtil.isBlankOrUndefined(FanUtil.toStringIfNullToEmpty(rightCustomerGroupId))) {
            FanUtil.errorAndMail("1307", "合并客户错误", StrUtil.format("数据错误，您 [合并到] 的客户没有对应的业主集团，请联系开发者操作！ customerid = {} ", rightId));
            throw new RuntimeException("数据错误，您 [合并到] 的客户没有对应的业主集团，请联系开发者操作！");

        }
        String groupIdJson = customerGroupService.getGroupIdJson(rightCustomerGroupId);


        for (Long leftId : leftIdArr) {
            // 查出对应业主集团数据
            Long leftCustomerGroupId = customerMapper.getCustomerGroupId(leftId);

            if (StrUtil.isBlankOrUndefined(FanUtil.toStringIfNullToEmpty(leftCustomerGroupId))) {
                FanUtil.errorAndMail("1307", "合并客户错误", StrUtil.format("数据错误，您合并的客户没有对应的业主集团，请联系开发者操作！ customerid = {} ", leftId));
                throw new RuntimeException("数据错误，您合并的客户没有对应的业主集团，请联系开发者操作！");

            }


            // DELETE proj_customer
            String deletedCustomerJson = deleteAndLog(
                    "SELECT * FROM `proj_customer` WHERE customerid IN ({});",
                    "DELETE FROM `proj_customer` WHERE customerid IN ({});",
                    leftId.toString()

            );


            // DELETE proj_project_z_customergroup
            String deletedCustomerGroupJson = deleteAndLog(
                    "SELECT * FROM `proj_project_z_customergroup` WHERE customergroupid IN ({});",
                    "DELETE FROM `proj_project_z_customergroup` WHERE customergroupid IN ({});",
                    leftCustomerGroupId.toString()

            );


            // UPDATE proj_customer_ref_chain_contact
            String contactIdSequence = updateAndLog(
                    "SELECT ref_id FROM `proj_customer_ref_chain_contact` WHERE customer_id IN ({}) AND active = 1",
                    "ref_id",
                    "UPDATE `proj_customer_ref_chain_contact` SET customer_id = {} WHERE customer_id IN ({})  AND active = 1",
                    leftId.toString(),
                    rightId
            );


            // UPDATE proj_project
            String projectIdSequence = updateAndLog(
                    "SELECT projectid FROM `proj_project` WHERE customerid IN ({}) AND projectid > 0",
                    "projectid",
                    "UPDATE `proj_project` SET customerid = {} , customergroupid = " + rightCustomerGroupId + " , group_id_json = '" + groupIdJson + "' WHERE customerid IN ({}) AND projectid > 0",
                    leftId.toString(),
                    rightId
            );


            // UPDATE pre_project_basicinfo
            String s1IdSequence = updateAndLog(
                    "SELECT npdfs1id FROM `pre_project_basicinfo` WHERE customerid IN ({}) AND active = 1",
                    "npdfs1id",
                    "UPDATE `pre_project_basicinfo` SET customerid = {} , customergroupid = " + rightCustomerGroupId + " , group_id_json = '" + groupIdJson + "' WHERE customerid IN ({}) AND active = 1",
                    leftId.toString(),
                    rightId
            );

            MergeLog mergeLog = new MergeLog(
                    IdUtil.getUId(),
                    leftId,
                    rightId,
                    deletedCustomerJson,
                    deletedCustomerGroupJson,
                    contactIdSequence,
                    projectIdSequence,
                    s1IdSequence
            );
            FanUtil.setBaseData(mergeLog);
            mergeLogMapper.insert(mergeLog);
        }

    }

    /**
     * @param ids 主键序列 proj_customer_merge_log.log_id
     */
    public void rollback(String ids) {
        if (ids != null) {

            List<MergeLog> mergeLogList = mergeLogMapper.selectBatchIds(Arrays.asList(ids.split(",")));
            for (MergeLog mergeLog : mergeLogList) {

                Long mergeCustomerId = mergeLog.getMergeCustomerId();

                //  proj_customer
                List<ProjCustomer> deletedCustomerList = JSON.parseArray(mergeLog.getDeletedCustomer(), ProjCustomer.class);
                deletedCustomerList.forEach(customer -> {
                    customerMapper.insert(customer);
                });


                //  proj_project_z_customergroup
                List<CustomerGroup> deletedCustomerGroupList = JSON.parseArray(mergeLog.getDeletedCustomerGroup(), CustomerGroup.class);
                deletedCustomerGroupList.forEach(customerGroup -> {
                    customerGroupMapper.insert(customerGroup);
                });


                // UPDATE proj_customer_ref_chain_contact
                String contactRefIdSequence = mergeLog.getContactRefIdSequence();
                if (!StrUtil.isBlankOrUndefined(contactRefIdSequence)) {
                    jdbcTemplate.execute(
                            StrUtil.format(
                                    "UPDATE `proj_customer_ref_chain_contact` SET customer_id = {} WHERE ref_id IN ({})  AND active = 1",
                                    mergeCustomerId,
                                    contactRefIdSequence
                            )
                    );
                }

                // UPDATE proj_project
                String projectIdSequence = mergeLog.getProjectIdSequence();
                if (!StrUtil.isBlankOrUndefined(projectIdSequence)) {
                    jdbcTemplate.execute(
                            StrUtil.format(
                                    "UPDATE `proj_project` SET customerid = {} WHERE projectid IN ({}) AND projectid > 0",
                                    mergeCustomerId,
                                    projectIdSequence
                            )
                    );
                }

                // UPDATE pre_project_basicinfo
                String s1IdSequence = mergeLog.getS1IdSequence();
                if (!StrUtil.isBlankOrUndefined(s1IdSequence)) {
                    jdbcTemplate.execute(
                            StrUtil.format(
                                    "UPDATE `pre_project_basicinfo` SET customerid = {} WHERE npdfs1id IN ({}) AND active = 1",
                                    mergeCustomerId,
                                    s1IdSequence
                            )
                    );
                }

            }


        }


    }

    private String deleteAndLog(String selectSql, String deleteSql, String leftIdSequence) {

        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(
                StrUtil.format(
                        selectSql,
                        leftIdSequence
                )
        );
        if (mapList == null || mapList.size() == 0) {
            return "";
        }

        jdbcTemplate.execute(
                StrUtil.format(
                        deleteSql,
                        leftIdSequence
                )
        );


        return JSON.toJSONString(mapList);
    }

    private String updateAndLog(String selectSql, String selectEntry, String updateSql, String leftIdSequence, Long rightId) {
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(
                StrUtil.format(
                        selectSql,
                        leftIdSequence
                )
        );
        if (mapList == null || mapList.size() == 0) {
            return "";
        }

        List<String> idList = FanUtil.mapListToList(mapList, selectEntry);

        jdbcTemplate.execute(
                StrUtil.format(
                        updateSql,
                        rightId,
                        leftIdSequence
                )
        );

        return String.join(",", idList);
    }


}
